package com.sa.commons.dao.hiber.batchUpdate;

import java.util.Iterator;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.sa.commons.dao.hiber.batchUpdate.inter.GenericBatchUpdate;

import com.sa.commons.dao.hiber.util.CreateHqlUtil;
import com.sa.commons.exception.DBDataErrorException;
import com.sa.commons.exception.DBErrorException;

public class GenericBatchUpdateHqlImpl<E> extends HibernateDaoSupport implements GenericBatchUpdate<E> {

	private static final Log log = LogFactory
			.getLog(GenericBatchUpdateHqlImpl.class);

	private Class<? extends E> entityClass;

	public GenericBatchUpdateHqlImpl(Class<? extends E> entityClass) {
		this.entityClass = entityClass;
	}

	@SuppressWarnings("unchecked")
	public void batchUpdate(Map<String, ?> equalsMap,
			Map<String, ? extends Object[]> inMap, Map<String, String> updateMap)throws DBErrorException,DBDataErrorException {
		log.debug("batchUpdate for class=" + entityClass.getName());
		try {
			StringBuffer hql = new StringBuffer("update "
					+ entityClass.getName() + " as entity set ");

			for (Iterator<?> iterator = updateMap.entrySet().iterator(); iterator
					.hasNext();) {
				Map.Entry<String, ?> entry = (Map.Entry<String, ?>) iterator
						.next();
				hql.append("entity.");
				hql.append(entry.getKey());
				hql.append("=");
				hql.append("\'" + entry.getValue() + "\'");
				if (iterator.hasNext()) {
					hql.append(",");
				}
			}
			
			hql.append(this.createQueryHql(equalsMap, inMap));
			System.out.println(hql);
			getSession().createQuery(hql.toString()).executeUpdate();
		} catch (RuntimeException re) {
			log.error("batchUpdate for class=" + entityClass.getName()
					+ " failed!", re);
			throw new DBErrorException("批量更新失败");
		}catch (Exception e) {
			log.error("batchUpdate for class=" + entityClass.getName()
					+ " failed!", e);
			throw new DBDataErrorException("批量更新失败");
		}

	}

	public void batchUpdate(Map<String, ?> equalsMap,
			Map<String, String> updateMap)throws DBErrorException,DBDataErrorException {
		this.batchUpdate(equalsMap, null, updateMap);
	}
	
	public Class<? extends E> getEntityClass() {
		return entityClass;
	}

	public void setEntityClass(Class<? extends E> entityClass) {
		this.entityClass = entityClass;
	}
	
	public String createQueryHql(Map<String, ?> equalsMap,
			Map<String, ? extends Object[]> inMap){
		return CreateHqlUtil.createQueryHql(equalsMap, inMap);
	}
	
}
